import axios from "axios";
import { userStore } from "@/store/module/user";
import { showFailToast, showLoadingToast } from "vant";

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 基础URL
  timeout: 30000, // 超时时间
  headers: {
    "Content-Type": "application/json", // 内容类型
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 设置loading状态（可选）
    if (config.showLoading) {
      showLoadingToast({
        message: config.loadingText || "加载中...",
        forbidClick: true,
      });
    }
    // 自动添加token
    const { token } = userStore();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { config } = response;
    // 关闭loading状态
    if (config.showLoading) {
      showLoadingToast().clear();
    }
    if (response.data?.code !== 200) {
      throw new Error(response.data?.msg || "请求失败");
    }
    return response.data;
  },
  (error) => {
    const { config } = error;
    // 关闭loading状态
    if (config?.showLoading) {
      showLoadingToast().clear();
    }
    // 处理无法重试的错误
    return handleError(error);
  }
);

// 错误处理函数
const handleError = (error) => {
  const store = userStore();
  // 根据不同状态码处理错误
  if (error.response) {
    const { status, data } = error.response;
    switch (status) {
      case 401:
        // 未授权，清除token并跳转到登录页
        if (store.isAuthenticated) {
          store.logout();
          // 使用router跳转而不是window.location，保留路由状态
          const currentPath = window.location.pathname + window.location.search;
          window.location.href = `/login?redirect=${encodeURIComponent(
            currentPath
          )}`;
        }
        showFailToast("登录已过期，请重新登录");
        break;
      case 403:
        showFailToast("没有权限访问此资源");
        break;
      case 404:
        showFailToast("请求的资源不存在");
        break;
      case 429:
        showFailToast("请求过于频繁，请稍后再试");
        break;
      case 500:
      case 502:
      case 503:
      case 504:
        showFailToast("服务器暂时不可用，请稍后再试");
        break;
      default:
        showFailToast(data?.msg || "请求失败");
    }
  } else if (error.request) {
    // 网络错误
    showFailToast("网络连接失败，请检查网络设置");
  } else {
    // 请求配置错误
    showFailToast("请求配置错误");
  }
  return Promise.reject(error);
};

// 封装get请求
export const get = (url, params = {}, config = {}) => {
  return request.get(url, { params }, config);
};

// 封装post请求
export const post = (url, data = {}, config = {}) => {
  return request.post(url, data, config);
};

// 封装put请求
export const put = (url, data = {}, config = {}) => {
  return request.put(url, data, config);
};

// 封装delete请求
export const del = (url, config = {}) => {
  return request.delete(url, config);
};
